/*
 * Created: 2022-08-25 20:38:13
 * Author : 涛涛涛
 */

import Taro from '@tarojs/taro';

/*
 * Created: 2022-07-07 08:54:44
 * Author : 涛涛涛
 */
const getRemNum = () => {
    try {
        return parseInt(document.querySelector('html').style.fontSize);
    } catch (error) {
        return 0;
    }
};
let figureWidth = Taro.getSystemInfoSync().windowWidth;
let remNum = getRemNum();
window.addEventListener('resize', function () {
    const windowWidth = Taro.getSystemInfoSync().windowWidth;
    // 此处做此种转换,是因为Taro在index中就进行了此中转换.自己封装的数据要与之同步
    figureWidth = windowWidth >= 640 ? 640 : windowWidth <= 320 ? 320 : windowWidth;
    remNum = getRemNum();
});
/** px转rpx */
const px_2_rpx = (px: number) => {
    return px / (figureWidth / 750);
};
/** rpx转px */
const rpx_2_px = (rpx: number) => {
    return rpx * (figureWidth / 750);
};
/** px转rem */
const px_2_rem = (px: number) => {
    return px / remNum;
};
/** rem转px */
const rem_2_px = (rem: number) => {
    return rem * remNum;
};

/** 后缀 */
let affix: 'rpx' | 'rem' | '' = '';
// 调用taro环境的函数,只执行一次.
let _px_2_unit: (px: number) => number = (px: number) => {
    const sysCtx = Taro.getEnv();
    if (sysCtx === Taro.ENV_TYPE.WEB) {
        affix = 'rem';
        _px_2_unit = px_2_rem;
    }
    if (sysCtx === Taro.ENV_TYPE.WEAPP) {
        affix = 'rem';
        _px_2_unit = px_2_rpx;
    }
    return _px_2_unit(px);
};
// 调用taro环境的函数,只执行一次.
let _unit_2_px: (px: number) => number = (unit: number) => {
    const sysCtx = Taro.getEnv();
    if (sysCtx === Taro.ENV_TYPE.WEB) {
        _unit_2_px = rem_2_px;
    }
    if (sysCtx === Taro.ENV_TYPE.WEAPP) {
        _unit_2_px = rpx_2_px;
    }
    return _unit_2_px(unit);
};

interface Px_2_unit {
    (px: number): number;
    (px: number, useAffix: true): string;
    (px: number, useAffix: false): number;
}
interface Unit_2_px {
    (px: number): number;
    (px: number, useAffix: true): string;
    (px: number, useAffix: false): number;
}
export const px_2_unit: Px_2_unit = (px: number, useAffix: boolean = false) => {
    const ret = !useAffix ? _px_2_unit(px) : _px_2_unit(px) + affix;
    return ret as any;
};
export const unit_2_px: Unit_2_px = (unit: number, useAffix: boolean = false) => {
    const ret = !useAffix ? _unit_2_px(unit) : _unit_2_px(unit) + affix;
    return ret as any;
};
export const getUnitAffix = () => affix;
